package kr.moiba.system.auth;

import java.util.Vector;

import kr.moiba.user.service.UserSvc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Lee Youngho
 *
 */

@Service("userAuthService")
@Transactional(readOnly = true)
public class UserAuthSvc implements UserDetailsService {

	@Autowired
    private UserSvc userSvc;

	@Override
	public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {

		User user = null;
		try {
			kr.moiba.user.domain.User authUser = userSvc.findbyAuth(userId);

			if(authUser != null){
				boolean enabled = true;
				if(authUser.getEnabled() != null && authUser.getEnabled() == 0){
					enabled = false;
				}
				
				boolean accountNonExpired = true;
				boolean credentialsNonExpired = true;
				boolean accountNonLocked = true;
				
				Vector<GrantedAuthority> authorities = new Vector<GrantedAuthority>();
				authorities.add(new  SimpleGrantedAuthority(authUser.getAuthority()));
				String password = authUser.getPw();
				user = new User(userId, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
	
}